﻿using System;
using System.Collections;
using System.IO;

namespace FeedbackNetwork.dataset
{
    class MnistFileParser
    {
        public static ArrayList ParseLabelFile(string data_path)
        {
            ArrayList result = new();
            BinaryReader bw;
            try
            {
                bw = new BinaryReader(new FileStream(data_path, FileMode.Open));
                uint data_int = ReadUInt(bw);
                uint length = ReadUInt(bw);

                for (uint i = 0; i < length; i++)
                {
                    data_int = bw.ReadByte();
                    result.Add(data_int);
                }
            }catch(Exception e)
            {
                Console.WriteLine("文件读取失败: " + data_path + "\n" + e.Message);
            }

            return result;
        }

        public static ArrayList ParseImageFile(string data_path)
        {
            ArrayList result = new();
            BinaryReader bw;
            try
            {
                bw = new BinaryReader(new FileStream(data_path, FileMode.Open));
                uint data_int = ReadUInt(bw);
                uint length = ReadUInt(bw);
                uint width = ReadUInt(bw);
                uint height = ReadUInt(bw);

                for (uint i = 0; i < length; i++)
                {
                    float[] temp_image = new float[width * height];

                    for(uint j = 0; j < width * height; j++)
                    {
                        uint s = bw.ReadByte();
                        temp_image[j] = s*2/255.0f-1f;
                    }

                    result.Add(temp_image);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("文件读取失败: " + data_path + "\n" + e.Message);
            }

            return result;
        }

        private static byte[] BigToSmall(byte[] source)
        {
            byte temp1 = source[0];
            byte temp2 = source[1];
            source[0] = source[3];
            source[1] = source[2];
            source[2] = temp2;
            source[3] = temp1;
            return source;
        }

        private static uint ReadUInt(BinaryReader reader)
        {
            byte[] m = reader.ReadBytes(4);
            m = BigToSmall(m);
            return BitConverter.ToUInt32(m);
        }
    }


}
